#!/usr/bin/env swift

import Foundation

func main() {
    let fileManager = FileManager.default
    
    // 获取脚本所在的目录
    let scriptPath = CommandLine.arguments[0]
    let scriptURL = URL(fileURLWithPath: scriptPath)
    let currentDirectory = scriptURL.deletingLastPathComponent().path
    
    // 查找 DevEcoStudio 目录 (5.0, 5.1, 5.2等版本)
    let homeDirectory = NSHomeDirectory()
    let huaweiPath = "\(homeDirectory)/Library/Application Support/Huawei"
    
    var targetDirectory: String?
    
    do {
        let contents = try fileManager.contentsOfDirectory(atPath: huaweiPath)
        let devEcoStudioDirs = contents.filter { $0.hasPrefix("DevEcoStudio") }.sorted()
        
        if let latestVersion = devEcoStudioDirs.last {
            targetDirectory = "\(huaweiPath)/\(latestVersion)"
            print("找到 DevEcoStudio 目录: \(latestVersion)")
        }
    } catch {
        // 如果没找到，使用默认版本
        targetDirectory = "\(huaweiPath)/DevEcoStudio5.0"
        print("未找到 DevEcoStudio 目录，使用默认: DevEcoStudio5.0")
    }
    
    guard let validTargetDirectory = targetDirectory else {
        print("❌ 无法确定目标目录")
        exit(1)
    }
    
    let backupName = "templates"
    let backupPath = "\(validTargetDirectory)/\(backupName)"
    
    print("开始备份代码块模板...")
    print("源目录: \(currentDirectory)")
    print("目标目录: \(backupPath)")
    
    do {
        // 如果备份目录已存在，先删除
        if fileManager.fileExists(atPath: backupPath) {
            print("删除现有备份...")
            do {
                try fileManager.removeItem(atPath: backupPath)
            } catch {
                print("⚠️ 无法删除现有备份，尝试备份到新位置...")
                let timestamp = Int(Date().timeIntervalSince1970)
                let newBackupPath = "\(validTargetDirectory)/templates_backup_\(timestamp)"
                print("新备份位置: \(newBackupPath)")
                try fileManager.copyItem(atPath: currentDirectory, toPath: newBackupPath)
                
                print("✅ 备份完成！")
                print("备份位置: \(newBackupPath)")
                print("📁 备份包含以下文件:")
                
                let contents = try fileManager.contentsOfDirectory(atPath: newBackupPath)
                for file in contents.sorted() {
                    print("  • \(file)")
                }
                
                print("🔄 使用方法:")
                print("1. 将包含此脚本的整个目录备份到网盘")
                print("2. 在新电脑上下载到任意位置（如桌面或下载文件夹）")
                print("3. 双击运行此脚本即可恢复代码块到DevEco Studio")
                return
            }
        }
        
        // 复制整个templates目录
        try fileManager.copyItem(atPath: currentDirectory, toPath: backupPath)
        
        print("✅ 备份完成！")
        print("备份位置: \(backupPath)")
        print("📁 备份包含以下文件:")
        
        // 列出备份的文件
        let contents = try fileManager.contentsOfDirectory(atPath: backupPath)
        for file in contents.sorted() {
            print("  • \(file)")
        }
        
        print("🔄 使用方法:")
        print("1. 将包含此脚本的整个目录备份到网盘")
        print("2. 在新电脑上下载到任意位置（如桌面或下载文件夹）")
        print("3. 双击运行此脚本即可恢复代码块到DevEco Studio")
        
    } catch {
        print("❌ 备份失败: \(error.localizedDescription)")
        exit(1)
    }
}

main()
